import {
	serverUrl
} from "@/config/config.js";
import Vue from 'vue'

Vue.prototype.$serverUrl = serverUrl;

let reqCount = 0,
	resCount = 0; //记录请求次数和响应次数
const request = (options) => {
	let header = {}

	header["Content-Type"] = options.contentType == "urlencoded" ? "application/x-www-form-urlencoded" :
		"application/json" ||
		"application/json";

	if (options.data) {} else {
		options.data = {}
	}
	if (!options.notToken && uni.getStorageSync("token")) {
		header.usertoken = uni.getStorageSync("token")
	}
	if (!options.notLoading && !options.notTips) {
		uni.showLoading();
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: options.method ? options.method : 'POST',
			url: serverUrl + options.url,
			data: options.data,
			header: header //如需其他配置可在此添加或先转换options.url，然后 ...options
		}).then((response) => {
			resCount++
			if (reqCount < resCount) uni.hideLoading(); //防止连续请求多个接口时loading闪现
			let res = response.data
			console.log('requestRes', res);
			if (res.code === -1) {
				if (uni.getStorageSync("token")) {
					tools.clearUserMessage()
				}
				uni.showToast({
					title: res.msg,
					icon: "none"
				})
				setTimeout(() => {
					uni.reLaunch({
						url: "/pages/index/index",
						complete: function(e) {
							console.log(e);
						}
					})
				}, 1000)

			} else if (options.notTips) {
				resolve(res);
			} else if (res.code === 1) {
				resolve(res);
			} else {
				uni.showToast({
					title: res.msg,
					icon: "none"
				})
			}
		}).catch(error => {
			resCount++
			if (reqCount === resCount) uni.hideLoading();
			let [err, res] = error;
			uni.showToast({
				title: error.data.msg,
				icon: "none"
			})
			reject(err)
		})
	});
}
export default request